package com.sunop.userservice.properties;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.StpUtil;
import com.sunop.userservice.mapper.UserMapper;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.lang.reflect.Field;
import java.util.Arrays;

@Configuration
public class RabbitMQConfig {

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();// 使用Jackson2JsonMessageConverter作为消息转换器(把消息转换成json，不然是序列化的)
    }

    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
            ConnectionFactory connectionFactory, MessageConverter jsonMessageConverter) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory); // 设置连接工厂
        factory.setMessageConverter(jsonMessageConverter); // 指定消息转换器
        return factory;
    }

    @Bean
    public SimpleRabbitListenerContainerFactory dynamicListenerContainerFactory(
            ConnectionFactory connectionFactory) {

        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setConcurrentConsumers(10); // 设置并发消费者数量
        factory.setMaxConcurrentConsumers(60); // 设置最大并发消费者数量
        return factory;
    }

    /**
     * 动态队列解析器（从MySQL查询）
     */

    @Bean(name = "dynamicClassQueueResolver") // 显式指定Bean名称
    public SimpleRabbitListenerContainerFactory dynamicClassQueueResolver(UserMapper userMapper) {
        return new SimpleRabbitListenerContainerFactory() {
            private final String[] EMPTY_ARRAY = new String[0];public String[] resolveQueues() {
                // 安全检查：用户是否登录
                if (!StpUtil.isLogin()) {
                    return EMPTY_ARRAY;
                }

                try {
                    int currentUserId = StpUtil.getLoginIdAsInt();
                    String classIds = String.valueOf(userMapper.getclassId(currentUserId));
                    return Arrays.stream(classIds.split(","))
                            .map(classId -> "class.queue." + classId.trim())
                            .toArray(String[]::new);
                } catch (Exception e) {
                    return EMPTY_ARRAY;
                }
            }

            private boolean isSaTokenContextReady() {
                try {
                    // 通过反射检查Sa-Token上下文是否就绪
                    Field contextField = SaManager.class.getDeclaredField("context");
                    contextField.setAccessible(true);
                    return contextField.get(SaManager.class) != null;
                } catch (Exception e) {
                    return false;
                }
            }
        };
    }

}